# -*- coding: utf-8 -*-
import os

import pytest

from Keywords.appkeys import App
from Keywords.interkeys import Inter
from Keywords.keyword import Web
from common.Logger import logger
from common.excel.Excel import get_reader


class Conf:
    """数据驱动运行类"""

    def __init__(self):
        # 设置分组信息
        self.feature = '测试项目'
        self.feature_idx = 0
        self.story = '测试分组'
        self.story_idx = 0
        # 保存一个模块里面所有的用例
        self.cases = []
        # 初始化关键字对象
        self.obj = None

        # 记录运行的sheet和用例的序号
        self.s_idx = 1
        self.c_idx = 1

        # 记录运行的用例类型
        self.case_type = 'web'

    def runCase(self, case_file='./lib/电商项目用例.xlsx', res_file="./lib/result-电商项目用例.xlsx"):
        """获取excel里面的用例，处理成列表，并且运行"""
        reader = get_reader(case_file)
        # writer = get_writer(case_file, res_file)

        # 一个sheet页面一个sheet页面读
        sheetname = reader.get_sheets()
        logger.info(sheetname)
        line = reader.readline()[1]
        casetype = line[1]
        if casetype == "APP":
            self.obj = App()
        else:
            self.obj = Web()

        self.case_type = 'web'

        # 遍历sheet
        for sheet in sheetname:
            # 设置当前读取的sheet页面
            reader.set_sheet(sheet)
            # 设置大分组名字
            self.feature = sheet
            self.feature_idx += 1
            self.story_idx = 0
            lines = reader.readline()
            # 统计用例的步骤
            case = []
            # 遍历行
            for i in range(1, len(lines)):
                line = lines[i]
                # 如果是模块
                if len(line[0]) > 1:
                    # 如果已经统计完了一个用例
                    if case:
                        self.cases.append(case)
                        if i == 1:
                            self.__run_pytest(1)
                        else:
                            self.__run_pytest()
                        case = []

                    # 记录模块名字
                    self.story = line[0]
                    self.story_idx += 1
                # 如果是用例
                elif len(line[1]) > 1:
                    if case:
                        self.cases.append(case)
                    # 重置case
                    case = []
                    case.append(line)
                # 如果是步骤
                else:
                    # 把步骤添加到用例列表里面
                    case.append(line)

            # 包存和运行最后一个模块的用例
            if case:
                self.cases.append(case)

            if self.cases:
                # 执行
                self.__run_pytest(0)

                self.s_idx += 1

        # 最后把代码名字还原
        os.rename('./ddt/test_%s_%s_%s.py' % (self.case_type, self.s_idx - 1, self.c_idx - 1),
                  './ddt/test_%s.py' % self.case_type)
        self.obj.quit()


    def __run_pytest(self, is_start=0):
        """执行用例"""
        logger.info('执行')
        logger.info(self.cases)
        # 刚开始跑第一个用例的时候
        if self.c_idx == 1:
            os.rename('./ddt/test_%s.py' % (self.case_type,),
                      './ddt/test_%s_%s_%s.py' % (self.case_type, self.s_idx, self.c_idx))
        else:
            try:
                os.rename('./ddt/test_%s_%s_%s.py' % (self.case_type, self.s_idx, self.c_idx - 1),
                          './ddt/test_%s_%s_%s.py' % (self.case_type, self.s_idx, self.c_idx))
            except:
                os.rename('./ddt/test_%s_%s_%s.py' % (self.case_type, self.s_idx - 1, self.c_idx - 1),
                          './ddt/test_%s_%s_%s.py' % (self.case_type, self.s_idx, self.c_idx))

        pytest.main(
            ['-s', './ddt/test_%s_%s_%s.py' % (self.case_type, self.s_idx, self.c_idx),
             '--alluredir', './result'])
        # 每执行一个用例，用例的序号加1
        self.c_idx += 1
        self.cases.clear()

    def runInterCase(self, case_file='./lib/HTTP接口用例.xlsx', res_file="./lib/result-HTTP接口用例.xlsx"):
        """获取excel里面的用例，处理成列表，并且运行"""
        reader = get_reader(case_file)
        # writer = get_writer(case_file, res_file)

        # 一个sheet页面一个sheet页面读
        sheetname = reader.get_sheets()
        self.obj = Inter()
        self.case_type = 'inter'

        self.s_idx = 1
        self.c_idx = 1

        # 遍历sheet
        for sheet in sheetname:
            # 设置当前读取的sheet页面
            reader.set_sheet(sheet)
            # 设置大分组名字
            self.feature = sheet
            self.feature_idx += 1
            self.story_idx = 0

            lines = reader.readline()
            # 统计用例的步骤
            case = []
            # 遍历行
            for i in range(1, len(lines)):
                line = lines[i]
                # 如果是模块
                if len(line[0]) > 1:
                    # 如果已经统计完了一个用例
                    if case:
                        self.cases.append(case)
                        self.__run_pytest()
                        case = []

                    # 记录模块名字
                    self.story = line[0]
                    self.story_idx += 1
                # 如果是用例
                elif len(line[1]) > 1:
                    if case:
                        self.cases.append(case)
                    # 重置case
                    case = []
                    case.append(line)
                # 如果是步骤
                else:
                    # 把步骤添加到用例列表里面
                    case.append(line)

            # 包存和运行最后一个模块的用例
            if case:
                self.cases.append(case)

            if self.cases:
                # 执行
                self.__run_pytest()

        # 每跑完一个sheet页，序号加一
        self.s_idx += 1

        # 最后把代码名字还原
        os.rename('./ddt/test_%s_%s_%s.py' % (self.case_type, self.s_idx - 1, self.c_idx - 1),
                  './ddt/test_%s.py' % self.case_type)


# 使用全局变量传参
conf = Conf()
